<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>大文件</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.5.0/axios.min.js"></script>
</head>
<body>
<input type="file" id="inputFile">
<button id="uploadFile">发送</button>
<script>
    const config = {
        chunkSize: 50 * 1024, // 每份切割大小
        minSize: 200 * 1024, // 超过该体积才开始切割
        chunkPost: {
            methods: 'post',
            url: 'http://localhost:7788/upload',
            params: {}
        },
        mergePost: {
            methods: 'get',
            url: 'http://localhost:7788/merge'
        }
    }

    function checkType(data, type = '') {
        const typeStr = Object.prototype.toString.call(data)
        const [, typeStr1 = ''] = typeStr.replace('/[\[\]]/g', '').split(' ')
        return type && type.toUpperCase() === typeStr1.toUpperCase()
    }
    function createUploadFileChunk(file) {
        if (!checkType(file, 'file')) throw new Error('不是文件类型');
        const chunks = []
        let startPos = 0
        const chunkSize = 50 * 1024 // 10k
        while (startPos < file.size) {
            const chunk = file.slice(startPos, startPos + chunkSize)
            chunks.push(chunk)
            startPos += chunkSize
        }
        return chunks
    }

    document.querySelector('#uploadFile').addEventListener('click', function (e) {
        const file = document.querySelector('#inputFile').files[0]
        const chunks = []
        let startPos = 0
        const chunkSize = 50 * 1024 // 10k
        while (startPos < file.size) {
            const chunk = file.slice(startPos, startPos + chunkSize)
            chunks.push(chunk)
            startPos += chunkSize
        }

        const httpList = chunks.map((item, index) => {
            const formData = new FormData()
            formData.set('name', `${file.name}_${index}`)
            formData.append('files', item)
            return window.axios.post('http://localhost:7788/upload', formData, {
                contentType: 'multipart/form-data'
            })
        })

        Promise.allSettled(httpList).then(list => {
            console.log(file)
            window.axios.get('http://localhost:7788/merge?name=' + encodeURIComponent(file.name))
        })

    })
</script>
</body>
</html>
